#include <stdio.h>
#include "ses_button.h"



// callback functions
pButtonCallback	rotary_Button 	= NULL;
pButtonCallback joystic_Button 	= NULL;

// flags to disable/enable further triggers, for debouncing
bool rotary_triggered 	= false;
bool joystick_triggered = false;



void button_init() {

	 DDR(BUTTON_ROTARY_PORT) &= ~(1<<BUTTON_ROTARY_PIN);
	 DDR(BUTTON_JOYSTICK_PORT) &= ~(1<<BUTTON_JOYSTICK_PIN);

	 BUTTON_ROTARY_PORT |= (1<<BUTTON_ROTARY_PIN);
	 BUTTON_JOYSTICK_PORT |= (1<<BUTTON_JOYSTICK_PIN);
	 PCICR |= (1<<PCIE0);

	 PCMSK0 |= (1<<BUTTON_ROTARY_PIN);
	 PCMSK0 |= (1<<BUTTON_JOYSTICK_PIN);

}

void button_setRotaryButtonCallback(pButtonCallback callback) {
	rotary_Button = callback;
}

void button_setJoystickButtonCallback(pButtonCallback callback) {
	joystic_Button = callback;
}

/*
 * Interrupt service routine for pin change interrupt 7:0.
 *
 * After one of the if-clauses is true, the *_triggered flag is set to true and
 * therefore disables further triggers. This is important for debouncing the
 * buttons. The flag will be set to false again when function *_pressed() is
 * called.
 */
ISR(PCINT0_vect) {

	if (rotary_Button && !rotary_triggered) {
		rotary_triggered = true;	// disable further triggers on rotary
		rotary_Button();
	}

	if (joystic_Button && !joystick_triggered) {
		joystick_triggered = true;	// disable further triggers on joystick
		joystic_Button();
	}

}

bool rotary_pressed() {
	rotary_triggered = false;	// enable triggers again on rotary
	return ((PIN(BUTTON_ROTARY_PORT) & (1 << BUTTON_ROTARY_PIN)) == 0);
}

bool joystick_pressed() {
	joystick_triggered = false;	// enable triggers again on joystick
	return ((PIN(BUTTON_JOYSTICK_PORT) & (1 << BUTTON_JOYSTICK_PIN)) == 0);
}
